import 'package:bot_toast/bot_toast.dart';
import 'package:easy_read_comic/controller/app_controller.dart';
import 'package:easy_read_comic/controller/me/me_controller.dart';
import 'package:easy_read_comic/internal/api/user_api.dart';
import 'package:easy_read_comic/models/user_model.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../models/app_model.dart';

class LoginController extends GetxController {
  final formKey = GlobalKey<FormState>();

  bool visibility = false;

  TextEditingController emailTextEditingController = TextEditingController();

  TextEditingController passwordTextEditingController = TextEditingController();

  void login() {
    if (formKey.currentState == null) {
      BotToast.showSimpleNotification(title: "系统错误");
      return;
    }
    if (formKey.currentState!.validate()) {
      UserApi()
          .login(emailTextEditingController.value.text,
              passwordTextEditingController.value.text)
          .then((response) {
        if (response.data["code"] == 1) {
          //登录成功
          var data = response.data["data"];
          BotToast.showSimpleNotification(title: "登录成功");
          //同步信息并储存数据到本地
          AppController()
              .storeAppDataAndSync(
            app: AppModel(
              true,
              Token: data["token"],
              User: UserModel.fromJson(data),
            ),
          )
              .then((value) {
            //先更新我的页面数据
            var meController = Get.put(MeController());
            meController.update();
            Get.back();
          });
        }
      });
    }
  }

  void changeVisibility() {
    this.visibility = !this.visibility;
    update();
  }
}
